package com.ld.security.auth.shiro.login.pass.impl;

import com.ld.security.auth.common.sys.po.LoginPo;
import com.ld.security.auth.shiro.config.ShiroProperties;
import com.ld.security.auth.shiro.login.jwt.JwtProperties;
import com.ld.security.auth.shiro.login.pass.PasswordService;
import com.ld.security.auth.shiro.login.pass.PasswordToken;
import com.ld.security.common.core.exception.ApiException;
import com.ld.security.common.core.util.AesCrypt;
import com.ld.security.common.core.util.CrptUtil;
import com.ld.security.common.core.util.JsonUtil;
import com.ld.security.common.core.util.StringUtil;
import com.ld.security.common.tomcat.util.RespUtil;
import com.ld.security.common.tomcat.util.SessionUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import static com.ld.security.auth.shiro.util.LoginUtil.getToken;


public class PasswordServiceImpl implements PasswordService {

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    ShiroProperties shiroProperties;

    @Override
    public String login(LoginPo po) {
        CrptUtil.encrpt(po);
        PasswordToken token =   new PasswordToken(po.getUsername(),po.getPassword(),SessionUtil.getIPAddress());
        token.setRememberMe(true);
        SecurityUtils.getSubject().login(token);

        String key =  AesCrypt.encrypt(JsonUtil.toJson(po));
        RespUtil.setHeader(jwtProperties.getTokenName(),key);

        //aes 加密
        return key;

    }

    @Override
    public String login() {

        String json =getToken();
        if(StringUtil.isNull(json)){
            ApiException.throw400("请登录");
        }
        json = AesCrypt.decrypt(json);

        LoginPo po =  JsonUtil.toObject(json,LoginPo.class);
        PasswordToken token =   new PasswordToken(po.getUsername(),po.getPassword(),SessionUtil.getIPAddress());
        token.setRememberMe(true);
        SecurityUtils.getSubject().login(token);
        return json;
    }

    @Override
    public boolean isUse() {
        return shiroProperties.isOpenCookie();
    }

    @Override
    public void logout() {
        SecurityUtils.getSubject().logout();
    }
}
